import { Platform } from '@angular/cdk/platform';
import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ElementRef,
  HostBinding,
  Input,
  OnDestroy,
  OnInit,
  TemplateRef,
  ViewEncapsulation,
} from '@angular/core';

import { AnchorComponent } from './anchor.component';

@Component({
  selector: 'fui-anchor-link',
  preserveWhitespaces: false,
  templateUrl: './anchor-link.component.html',
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AnchorLinkComponent implements OnInit, OnDestroy {
  @HostBinding('class') hostClass = 'fui-anchor-link';
  @HostBinding('class.fui-anchor-link-active') active = false;

  /** The href to jump */
  @Input() href = '#';

  titleString: string | null = '';
  titleTemplate: TemplateRef<any>;

  @Input()
  set title(value: string | TemplateRef<void>) {
    if (value instanceof TemplateRef) {
      this.titleString = null;
      this.titleTemplate = value;
    } else {
      this.titleString = value;
    }
  }

  constructor(
    public elementRef: ElementRef,
    private anchorComponent: AnchorComponent,
    private cdr: ChangeDetectorRef,
    private platform: Platform,
  ) { }

  ngOnInit(): void {
    this.anchorComponent.registerLink(this);
  }

  goToClick(e: Event): void {
    e.preventDefault();
    e.stopPropagation();
    if (this.platform.isBrowser) {
      this.anchorComponent.handleScrollTo(this);
    }
  }

  markForCheck(): void {
    this.cdr.markForCheck();
  }

  ngOnDestroy(): void {
    this.anchorComponent.unregisterLink(this);
  }
}
